/*
 * @AaronChen based on grunt-contrib-compass
 * http://gruntjs.com/
 *
 * Copyright (c) 2013 Sindre Sorhus, contributors
 * Licensed under the MIT license.
 */

'use strict';

var fs = require('fs');
var gruntTextReplace = require('../../node_modules/grunt-text-replace');

var App = require("../../../infrastructure/app/model").App;
var Subscription = require("../../../infrastructure/subscription/model").Subscription;

module.exports = function (grunt) {
  var compass = require('../../node_modules/grunt-contrib-compass/tasks/lib/compass').init(grunt);

  function compile(args, cb) {

    var child = grunt.util.spawn({
      cmd: args.shift(),
      args: args
    }, function (err, result, code) {
      if (code === 127) {
        grunt.warn(
          'You need to have Ruby and Compass installed ' +
          'and in your system PATH for this task to work. ' +
          'More info: https://github.com/gruntjs/grunt-contrib-compass'
        );
      }

      // `compass compile` exits with 1 and outputs "Nothing to compile"
      // on stderr when it has nothing to compile.
      // https://github.com/chriseppstein/compass/issues/993
      // Don't fail the task in this situation.
      if (code === 1 && !/Nothing to compile/g.test(result.stderr)) {
        grunt.warn('↑');
      }

      cb();
    });
    if (child) {
      child.stdout.pipe(process.stdout);
      child.stderr.pipe(process.stderr);
    }
  }

  grunt.registerMultiTask('compass_customized', 'Compile Sass to CSS using Compass', function () {

    var me = this;


    var dir = '.tmp/.requires/';

      var options = this.options();
      var cb = me.async();

    // display compilation time
    if (!options.clean) {
      options.time = true;
    }

    // create a function to retroactively add a banner to the top of the
    // generated files, if specified
    var bannerCallback = compass.buildBannerCallback(grunt, options);
    // create a temporary config file if there are 'raw' options or
    // settings not supported as CLI arguments
    var configContext = compass.buildConfigContext(options);

    configContext(function (err, path) {
      if (err) {
        grunt.warn(err);
      }

      if (path) {
        //args.push('--config', path);
      }

        var run = function() {
            for (var i = 0; i < me.requiresFiles.length; i++) {
                // get the array of arguments for the compass command
                var args = compass.buildArgsArray(options);
                for(var j = 0; j < args.length; j++) {
                    if(args[j] === 'pending-sass-dir'){
                        args[j] = me.requiresFiles[i].path;
                    } else if(args[j] === 'pending-theme') {
                        args[j] = 'ext/themes/' + me.requiresFiles[i].theme + '/img';
                    } else if(args[j] === 'pending-fonts-dir') {
                        args[j] = 'ext/themes/' + me.requiresFiles[i].theme + '/font/';
                    }
                }
                compile(args, function () {
                    bannerCallback();
                    cb();
                });
            }
        };

        var contains = function(a, obj) {
            for(var i = 0; i < a.length; i++) {
                if(a[i] === obj){
                    return true;
                }
            }
            return false;
        }

        var genRequiresFileForApp = function(app){
            var ret = [];

            var path = dir + app.id;
            var contents = "@import '../../../ext/themes/" + app.theme + "/style/_theme'; \n";

            grunt.file.expand({ filter: 'isFile'}, 'ext/themes/' + app.theme + '/widget/**/*/*.scss').forEach(function(path){

                contents += "@import '../../../" + path + "'; \n";
            });

            var codes = [];
            for (var i = 0; i < app.subscriptions.length; i++) {
                codes.push(app.subscriptions[i].code);
            }

            var themeConfig = grunt.file.readJSON('ext/themes/' + app.theme + '/theme.json', {encoding: 'utf8'});
            for(var code in themeConfig.layouts) {
                var layout = themeConfig.layouts[code];

                if (contains(codes, code)) {
                    contents += "@import '../../../ext/components/" + code + "/client/layouts/" + layout +"/style/_layout'; \n";
                }
            }
            grunt.file.write(path + '/' + app.id + '.scss', contents);
            ret.push({appId: app.id, theme: app.theme, path: path});

            return ret;
        };

        me.requiresFiles = [];
        if (!!options.app) {
            App.findById(options.app).exec(function(err, app) {
                App.populate(app, { path: 'subscriptions' }, function (err, app) {
                    var ret = genRequiresFileForApp(app);
                    me.requiresFiles = me.requiresFiles.concat(ret);
                    run();

                });
            });
        } else {
            App.find().exec(function(err, apps) {
                App.populate(apps, { path: 'subscriptions' }, function (err, apps) {
                    for (var i = 0; i < apps.length; i++) {
                        var ret = genRequiresFileForApp(apps[i]);
                        me.requiresFiles = me.requiresFiles.concat(ret);
                    }
                    run();
                });
            })
        }

    });
  });
};
